﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.IBLL;
using AiXiu.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.WebSite
{
    /// <summary>
    /// 编辑个人资料页
    /// </summary>
    public partial class PersonalEdit : Page
    {
        private District district;
        private ListItem ddlTips = new ListItem("- 请选择 -", "");

        public PersonalEdit()
        {
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(fileStream, Encoding.Default))
                {
                    string distinctStr = reader.ReadToEnd();
                    //json反序列化为District对象
                    district= JsonConvert.DeserializeObject<District>(distinctStr);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //读取当前登录的用户信息
                TBUsers user = IdentityManager.ReadUser();
                txtNickName.Text = user.NickName;
                ddlSex.SelectedValue = user.Sex.ToString();
                if (user.Birthday != null)
                {
                    txtBirthday.Text = user.Birthday.Value.ToString("yyyy-MM-dd");
                }

                //显示地址
                if (!string.IsNullOrEmpty(user.Address))
                {
                    string[] addArr = user.Address.Split(' ');
                    string province = addArr[0];
                    string city = addArr[1];
                    BindProvinces(province);
                    BindCitys(province, city);
                }
                else
                {
                    BindProvinces();
                    BindCitys("");
                }

                //显示爱好
                if (!string.IsNullOrEmpty(user.Hobby))
                {
                    for(int n = 0; n < cblHobby.Items.Count; n++)
                    {
                        string value = cblHobby.Items[n].Value;
                        if (user.Hobby.Contains(value))
                        {
                            cblHobby.Items[n].Selected = true;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 更新按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnProfile_Click(object sender, EventArgs e)
        {
            //1、读取当前用户在页面输入的信息
            TBUsers profile = IdentityManager.ReadUser();
            profile.NickName = txtNickName.Text;
            profile.Sex = ddlSex.SelectedIndex;
            if (!string.IsNullOrEmpty(txtBirthday.Text))
            {
                profile.Birthday = DateTime.Parse(txtBirthday.Text);
            }
            //user.Address = ddlProvince.SelectedValue + " " + ddlCity.SelectedValue;
            profile.Address = $"{ddlProvince.SelectedValue} {ddlCity.SelectedValue}";
            List<string> hobbyList = new List<string>();
            foreach (ListItem item in cblHobby.Items)
            {
                if (item.Selected)
                {
                    hobbyList.Add(item.Value);
                }
            }
            profile.Hobby = string.Join(" ", hobbyList);

            //2、在数据库更新信息
            IUserBLL userBLL = new UserBLL();
            OperResult<TBUsers> operResult = userBLL.EditUser(profile);
            if (operResult.StatusCode == StatusCode.Succeed)
            {
                //3、更新用户的缓存信息
                IdentityManager.SaveUser(profile);
                Response.Redirect("Personal.aspx");
            }
            else
            {
                this.Alert("deiterror", operResult.Message);
            }
        }

        /// <summary>
        /// 省份选项索引变更事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCitys(ddlProvince.SelectedValue);
        }

        /// <summary>
        /// 绑定省份下拉框
        /// </summary>
        /// <param name="provinceName">省份名称</param>
        private void BindProvinces(string provinceName=null)
        {
            //绑定省份列表
            ddlProvince.DataSource = district.Provinces;
            ddlProvince.DataValueField = "ProvinceName";
            ddlProvince.DataTextField = "ProvinceName";
            ddlProvince.DataBind();

            ddlProvince.Items.Insert(0, ddlTips);
            //设置省份默认选中
            if (string.IsNullOrEmpty(provinceName))
            {
                ddlProvince.SelectedIndex = 0;
            }
            else
            {
                ddlProvince.SelectedValue = provinceName;
            }
        }

        private void BindCitys(string provinceName,string cityName = null)
        {
            //没有选择省份时，清空城市列表
            if (string.IsNullOrEmpty(provinceName))
            {
                ddlCity.Items.Clear();
                ddlCity.Items.Add(ddlTips);
                return;
            }

            //未找到省份名称时，清空城市列表
            Province province= district.Provinces.SingleOrDefault(a => a.ProvinceName == provinceName);
            if (province == null)
            {
                ddlCity.Items.Clear();
                ddlCity.Items.Add(ddlTips);
                return;
            }

            //绑定省份下的城市列表
            ddlCity.DataSource = province.Citys;
            ddlCity.DataValueField = "CityName";
            ddlCity.DataTextField = "CityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, ddlTips);

            //设置城市默认选中项
            if (!string.IsNullOrEmpty(cityName))
            {
                ddlCity.SelectedValue = cityName;
            }
            else
            {
                ddlCity.SelectedIndex = 0;
            }
        }

    

    }
}